//
//  SBViewController.m
//  SBPageController
//
//  Created by leeszi on 07/19/2016.
//  Copyright (c) 2016 leeszi. All rights reserved.
//

#import "SBViewController.h"
#import "ViewController.h"
#import "SBNaviSegment.h"

const CGFloat itemWidth = 60;
const CGFloat itemHeight = 44;

@interface SBViewController ()
@property (nonatomic, strong) NSArray *pages;
@end

@implementation SBViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    ViewController *vc1 = [[ViewController alloc] init];
    vc1.idx = 0;
    vc1.view.backgroundColor = [UIColor greenColor];
    
    ViewController *vc2 = [[ViewController alloc] init];
    vc2.idx = 1;
    vc2.view.backgroundColor = [UIColor yellowColor];

    ViewController *vc3 = [[ViewController alloc] init];
    vc3.idx = 2;
    vc3.view.backgroundColor = [UIColor blueColor];

    self.pages = @[vc1, vc2, vc3];
    
    [self setViewController:self.pages[0]];
    
    SBNaviSegment *nav = [[SBNaviSegment alloc] init];
    nav.backgroundColor = [UIColor yellowColor];
    nav.pageController = self;
    nav.indicatorPadding = 8;
    nav.indicatorLeftMargin = 10;
    nav.indicatorRightMargin = 10;
    self.navigationItem.titleView  = nav;
    self.navigationItem.titleView.frame = CGRectMake(0, 0, itemWidth * self.pages.count, itemHeight);
    nav.items = @[@"班级圈", @"家长圈", @"空空空"];
    
    [nav setDotForIndex:1];
}

- (UIViewController *)controllerForIndex:(NSInteger)index {
    if (index < 0) {
        return nil;
    }
    
    if (index >= self.pages.count) {
        return nil;
    }
    
    return self.pages[index];
}

- (UIViewController *)pageController:(SBPageController *)pageController viewControllerBeforeViewController:(UIViewController *)viewController {
    NSInteger idx = [self.pages indexOfObject:viewController];
    return [self controllerForIndex:--idx];
}

- (UIViewController *)pageController:(SBPageController *)pageController viewControllerAfterViewController:(UIViewController *)viewController {
    NSInteger idx = [self.pages indexOfObject:viewController];
    return [self controllerForIndex:++idx];
}

- (void)childDidScrollOffset:(CGFloat)offset {
    SBNaviSegment *nav =  (SBNaviSegment *)self.navigationItem.titleView;
    [nav moveIndicator:offset];
}

- (void)childDidAppear:(UIViewController *)child {
    SBNaviSegment *nav =  (SBNaviSegment *)self.navigationItem.titleView;
    nav.selectedIndex = [self.pages indexOfObject:child];
    [nav setNeedsDisplay];
}

@end
